from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from QQLoginTool.QQtool import OAuthQQ
from django.views import View
from django.contrib.auth import login
from django.conf import settings
# Create your views here.
from oauth.models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django_redis import get_redis_connection
from users.models import User
# 合并购物车
from carts.utils import get_carts


class QQLoginView(View):
    def get(self, request):
        # 获取qq登录成功后的跳转
        next = request.GET.get('next')
        if next is None:
            next = '/'
        # 1.初始化创建的qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        # 2.调用方法生成跳转链接
        login_url = qq.get_qq_url()
        print('111111111111111111111111111111')
        # 3.返回跳转链接
        return JsonResponse({'login_url': login_url})


# qq登录后请求的页面



class QQCallBackView(View):
    def get(self, request):
        # 1.获取code值和state
        code = request.GET.get('code')
        print(code)
        state = request.GET.get('state')
        if code is None or state is None:
            return JsonResponse({'error': '缺少数据'}, status=400)
        # 生成qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        try:
            # ---------------------------获取access_token出错---------------------------------------------------------------------------------------
            # 3.调用方法获取access_token值
            access_token = qq.get_access_token(code)
            # 4.调用方法获取open_id的值
            open_id = qq.get_open_id(access_token)
        except:
            return JsonResponse({'errorr': '网络错误'}, status=400)
        # 判断openid是否绑定过美多用户
        try:
            # 如果qq号和手机号进行了绑定
            qq_user = OAuthQQUser.objects.get(openid=open_id)
        except:
            # qq未绑定过
            # 对open_id 进行加密
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({'openid': open_id}).decode()
            # 异常的话将页面跳转到qq绑定手机号页面，将加密的数据发送给未绑定页面
            return render(request, 'oauth_callback.html', {'token': openid})


        # 进行绑定--------------------
        # 没有异常说明qq查询到绑定用户
        # 状态保持
        login(request, qq_user.user)
        # 将用户名写入cookie方便在页面中展示
        response = redirect(state)
        response.set_cookie('username', qq_user.user.username, 60 * 60 * 2)
        response = get_carts(request, response, qq_user.user)
        return response

    def post(self, request):
        '''
                绑定qq用户
        :param request:
        :return:
        '''
        # 1.获取数据
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('pwd')
        sms_code = data.get('sms_code')
        # 获取隐藏的标签中的数据   也就是 oppen_id 数据
        openid = data.get('access_token')
        # 2.验证数据
        # 短信验证
        client = get_redis_connection('verify_code')
        real_sms_code = client.get('sms_code_%s' % mobile)
        if real_sms_code is None:
            return render(request, 'oauth_callback.html', {'errmsg': '短信验证码已失效'})
        if sms_code != real_sms_code.decode():
            return render(request, 'oauth_callback.html', {'srrmsg': '短信验证码错误'})
        # 3.绑定数据
        try:
            user = User.objects.get(mobile=mobile)
            # check_password   判断密码是否正确
            if not user.check_password(password):
                return render(request, 'oauth_callback.html', {'errmsg': '密码错误'})
        except:
            # 当前手机未注册成多美商城用户，使用当前手机号创建一个用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        # 将 openid绑定表中
        # 解密  openid
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            # 解密
            data = tjs.loads(openid)
        except:
            return render(request, 'oauth_callback.html', {'errmsg': 'openid异常'})
        # 获取
        openid = data.get('openid')
        # 将用户名和qq号的openid保存到数据库中
        OAuthQQUser.objects.create(openid=openid, user=user)
        response = redirect('/')
        response = get_carts(request, response,user)
        return response.set_cookie('username', user, 60 * 60 * 2)
